package com.longagoewk.springboot.controller.manageController;

import com.longagoewk.springboot.entity.ResultMessage;
import com.longagoewk.springboot.entity.UserBean;
import com.longagoewk.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
public class M_indexController {


    @Autowired
    UserService userService;

    @Autowired
    private HttpServletRequest request;

    @RequestMapping("/M_index")
    public String mIndex(){
        return "manage/M_index";
    }

    //登录
    @RequestMapping("/login")
    @ResponseBody
    public ResultMessage checkLogin(String username, String password, HttpServletRequest request) {
        ResultMessage lr = new ResultMessage();
        UserBean userBean = new UserBean();
        userBean.setUsername(username);
        userBean.setPassword(password);
        UserBean loginUser = userService.getUser(userBean);
        if (loginUser == null) {
            lr.setFlag("failed");
            lr.setData("用户未注册");
        } else {
            if (loginUser.getPassword().equals(password)) {
                request.getSession().setAttribute("user", loginUser);
                lr.setFlag("success");
                lr.setData("登录成功");
                lr.setUrl("M_main");
            } else {
                lr.setFlag("failed");
                lr.setData("密码错误");
            }
        }
        return lr;
    }

    //登出
    @RequestMapping("/logout")
    public String Logout() {
        request.getSession().setAttribute("user", null);
        return "manage/M_index";
    }

    //更新密码界面
    @RequestMapping("/M_changepasswd")
    public String Changepasswd() {
        return "manage/M_changepasswd";
    }

    //更新密码
    @RequestMapping("/changePassword")
    @ResponseBody
    public ResultMessage ChangePassword(String username, String password) {
        ResultMessage message = new ResultMessage();
        UserBean userBean = new UserBean();
        userBean.setUsername(username);
        userBean.setPassword(password);
        if (userService.updataUser(userBean)) {
            message.setFlag("success");
            message.setData("密码修改成功");
            message.setUrl("M_main");
        } else {
            message.setFlag("error");
            message.setData("密码修改失败");
        }
        return message;
    }


}
